/**
 * @html common.multiPopup
 * @description 通用多选弹出框js实现
 * 
 * @since 2011-11-17
 */
Ccay.Module.define("Ccay.Component.MultiPopup", function(page, $S) {

	/**
	 * 多选弹出框页面初始化
	 */
	var servicePath = "";
	var popupBean = "";

	var isInit = false; 
	var historyGridInit = false;

	page.init = function(bean, parentContext) {
		if (typeof bean.condRender == "function") {
			$S("#popup_cond_div").html(bean.condRender())
			//控件初始化
			Ccay.UI.init("#popup_cond_div");
			
			var btnHtml =['<SPAN id=btn_popup_mutil class="ccay-button search default" ><A class="ccay-icon search"></A><LABEL>'+ $.i18n.prop("ccay.common.button.search") +'</LABEL></SPAN>'];
			btnHtml.push('<SPAN id=reset class="ccay-button reset"  onclick =$(this).parents("form").ccayReset()  ><A class="ccay-icon reset"></A><LABEL>'+ $.i18n.prop("ccay.common.button.reset") +'</LABEL></SPAN>')
			$S("#popup_cond_div").append(btnHtml.join(""));
		} else if(bean.buttonIsCenter){
			initConditionArea(bean.columns, bean.buttonIsCenter);
		}else{
			initConditionArea(bean.columns);
		}
		
		//如果 servicePath 未传入值，则使用ajax属性中的 url
		if(!bean.servicePath){
			var currUrl = bean.ajax.url;
			bean.servicePath = currUrl.indexOf("/page") == -1 ? currUrl : currUrl.substring(0,currUrl.indexOf("/page")) + currUrl.substring(currUrl.indexOf("?"),currUrl.length);
		}
		
		popupBean = bean;
		servicePath = bean.servicePath;

		if (typeof(bean.initRender) === "function") {
			bean.initRender($S("#popup_cond_div"), self, $S);
		}
		// 将预置条件设置如查询表单中
		if (typeof popupBean.queryParam == "function")
			$S("#popup_cond_div").jsonData(popupBean.queryParam());
		else if(typeof popupBean.queryParam == "object"){
			$S("#popup_cond_div").jsonData(popupBean.queryParam);
		}
		popupBean.defaultParam && $S("#popup_cond_div").jsonData(popupBean.defaultParam);

		
		if(bean.uniqueKey && Ccay.History.isSupport(bean) &&  Ccay.History.hasHistory({historyKey : getHistoryKey()})){
			var historyList = Ccay.History.getHistory(getHistoryKey());
			if(historyList.length){
				$("#ipopup_tab").prepend($("#ipopup_tab").find("#ipopup_tab_history"));
				popupBean.hasHistory = true;
				initHistoryGrid();
			}else{
				$("#ipopup_tab_history").remove()
			}
		}else{
			$("#ipopup_tab_history").remove()
		}
		$("#ipopup_tab").ccayTab({
			fnBeforeSelectItem : function(tabId){
				isInit && cynchroOnSelected(tabId == "ipopup_tab_all" ? "#popupLeftTable" : "#popupHistoryTable");
			}
		});
		$("#ipopup_tab_right").ccayTab();
		initRightTable();
		initLeftTable();
		var tab_manager = $("#ipopup_tab").manager();
		$("#btn_popup_mutil").bind("click",function(){
			tab_manager.getSelectedItemId() != 'ipopup_tab_all' && tab_manager.selectItem('ipopup_tab_all');
		});
	};
	
	function getHistoryKey(){
		return popupBean.historyKey || popupBean.servicePath
	}
	
	function allClickHandle(grid){
		if(grid && grid.getHeadPanel){
			grid.getHeadPanel().find("td.igrid-selectAll").unbind("click.selectAll").bind("click.selectAll",function(){
			   var grid = $(this).parents(".ccay-igrid:first").manager(), selected = $(this).parent().toggleClass("igrid-selected").hasClass("igrid-selected");
			   if(grid.dom.id() == "popupRightTable"){
			   		var leftGrid = $("#popupLeftTable").manager(), historyGrid = $("#popupHistoryTable").manager();
					grid.reBind([]);
					leftGrid.op.Storage.each(function(leftData){
						leftData._selected = false;
					}); 
					leftGrid.reBind();
					if(historyGrid && historyGrid.op){
						historyGrid.op.Storage.each(function(data){
							data._selected = false;
						});
						historyGrid.reBind();
					}
			   }else{
			   		var rightGrid =  $("#popupRightTable").manager(), dataset = rightGrid.op.Storage.dataset,
			   		dataCache = {},selectedCache ={};
					grid.op.Storage.each(function(data){
						dataCache[Ccay.DataHelper.getObj(popupBean.uniqueKey, data)] = data;
						data._selected = selected ;
					})
			   		rightGrid.op.Storage.each(function(data){
		   				selectedCache[Ccay.DataHelper.getObj(popupBean.uniqueKey, data)] = data;
					});
					for(var value in dataCache){
						if(selectedCache[value]){
							selectedCache[value]._selected = selected;
						}else{
							selected && dataset.push($.extend({},dataCache[value],{_index : null}));
						}
					}
					if(selected){
						grid.getBodyPanel().find("tr.grid-row").attr("class","grid-row igrid-selected");
					}else{
						grid.getBodyPanel().find("tr.grid-row").removeClass("igrid-selected")
						rightGrid.getHeadPanel().find("tr.igrid-selected").removeClass("igrid-selected");
						dataset = rightGrid.op.Storage.filter(function(data){
		   					return data._selected;
						});
					}
			   		rightGrid.reBind(dataset);
			   		rightGrid.getHeadPanel().find("div.g-sort").removeClass("asc desc");
			   }
			   return false;
			})
		}else return false;
	}
	/**
	 * @description 初始化数据集合grid
	 */
	function initLeftTable() {
		var columns = [{columnType: 'select',multi : true,field : popupBean.uniqueKey}];
		$.each(popupBean.columns,function(){
			if(this.id){
				this.field = this.id;
				if(this.id.indexOf("\.")){
					this.field = this.id;
					this.displayField = "{0} ? {1} : ''".formatText(this.field.split("\.")[0], this.field);
				}
			}
			if(!this.width){
				this.width = 120;
			}
			columns.push($.extend({},this));
		});
		//查询请求地址
		if(!popupBean.ajax){
			var array = servicePath.split('?');
			var serviceUrl =( popupBean.openPage === false || popupBean.openPage == "false" )? servicePath : (array.length> 1 ? array[0]+"/page/{0}/{1}?"+array[1] : servicePath+"/page/{0}/{1}");
		}
		var options={
			shiftSelectMode : false,
			customSetting:false,
			autoLoad: popupBean.autoLoad === false ? false : true,  
			showPager: (popupBean.showPager === false || popupBean.noPage === true || popupBean.noPage == "true" )? false : true, 
			fnDataBindComplete : function(){
				var grid = this;
				if(isInit){
					cynchroLeftTable();
					
				}else{
					isInit = "wait";
				}
				setTimeout(function(){
					checkAllStatus(grid);
					allClickHandle($S("#popupLeftTable").manager());
				},10)
			},
			columns: columns,
			width : popupBean.gridWidth || 445,
			height : ( popupBean.noPage === true || popupBean.noPage == "true" ) ? 393 : 365,
			fnBeforeRequest : function(op){
				var bool = $.isEmptyObject(op.ajax.data);
				if(bool && (popupBean.allowEmptyCondition===false)){
					Ccay.UI.showMessage("ccay.popup.label.inputtip","warn");
					if(op.Storage.dataset.length){
						$S("#popupLeftTablePager").find("div.ccay-pager-text").addClass("hide");
						$S("#popupLeftTablePager").find("div.ccay-pager-panel").removeClass("hide");
					}
					return false;
				}

				if(op.ajax.oldData == op.ajax.data){
					return true;
				}
				
				//op.ajax.data 是否有值，是否要进行封装
				op.ajax.url = popupBean.ajax ? popupBean.ajax.url : serviceUrl;
				if(!bool && popupBean.paramToJsonStr){
					op.ajax.url += (op.ajax.url.indexOf("?") > 0 ? "&" : "?")+popupBean.paramToJsonStr+"={"+Ccay.Core._ajax.serialize(op.ajax.data)+"}";
					op.ajax.data = {};
				}
				
				if(popupBean.queryParam){
					//pengmingxing WX219318 修正popup中使用igrid:true,queryParam不能使用函数返回参数。
					op.ajax.data = $.extend({},typeof popupBean.queryParam == "function"?popupBean.queryParam():popupBean.queryParam, op.ajax.data); 
				}
				op.ajax.oldData = op.ajax.data;
			},
			ajax : $.extend({url:serviceUrl},popupBean.ajax),
			operation:{
				search:{
					autoSearch : typeof popupBean.autoSearch == "boolean" ? popupBean.autoSearch : true,
					//查询条件区域id选择器
					panel:'#popupSearchForm',
					btn : "#btn_popup_mutil"
				}
			}
			,pagerOp:{
				mode : null,
				showLast: popupBean.showLast!==false,
				
				pageInf: {
					pageSize: popupBean.pageSize || Ccay.UI.Config.pager.defaultSize
				},
				pageSizes: popupBean.pageSizeList || Ccay.UI.Config.pager.pageSizes
			}

		};
		var currLeftOptions = $.type(popupBean.leftTableOptions) == "object" ? popupBean.leftTableOptions : (popupBean.event && popupBean.event.left);
		$S("#popupLeftTable").igrid($.extend(options,currLeftOptions)).delegate("tr.grid-row","dblclick",function(e){
			var tr = $(this);
			if(!tr.hasClass("ipopup-selected")){
				$(this).find("td.grid-select").click();
			}
		})
		var manager = 	$S("#popupLeftTable").manager();
		manager.op && manager.op.Storage && manager.op.Storage.Trigger.select.add(page.leftTriggerFn)
		
	}
	
	page.leftTriggerFn = function(data, select){
		var rightGrid = $S("#popupRightTable").manager(), rightStorage = rightGrid.op.Storage;
		if(select){
			rightStorage.dataset.push($.extend({},data,{_index:null}));
			rightGrid.reBind();
			rightGrid.getHeadPanel().find("div.g-sort").removeClass("asc desc");
		}else{
			rightStorage.each(function(rdata){
				
				if(Ccay.DataHelper.getObj(popupBean.uniqueKey, rdata) == Ccay.DataHelper.getObj(popupBean.uniqueKey, data)){
					rightStorage.destroyItem(rdata._index);
					return false;
				}
			})
			rightGrid.reBind();
			rightGrid.getHeadPanel().find("div.g-sort").removeClass("asc desc");
		}
	}

	function initHistoryGrid(){
		historyGridInit = true
		var columns = [{columnType: 'select',multi : true,field : popupBean.uniqueKey}];
		$.each(popupBean.columns,function(){
			if(this.id){
				this.field = this.id;
				if(this.id.indexOf("\.")){
					this.field = this.id;
					this.displayField = "{0} ? {1} : ''".formatText(this.field.split("\.")[0], this.field);
				}
			}
			if(!this.width){
				this.width = 110;
			}
			columns.push($.extend({},this));
		});
		var options={
			shiftSelectMode : false,
			customSetting:false,
			showPager:false,
			columns:columns ,
			width : popupBean.gridWidth || 445,
			autoLoad : false,
			fnDataBindComplete : function(){
				var grid = this;
				setTimeout(function(){
					checkAllStatus(grid);
				},10)
			},
			height : 393
		};
		var currHistoryOptions = $.type(popupBean.historyTableOptions) == "object" ? popupBean.historyTableOptions : {};
		$S("#popupHistoryTable").igrid($.extend(options,currHistoryOptions)).delegate("tr.grid-row","dblclick",function(e){
			$(this).find("td.grid-select").click();
		}).bind('selectstart',function(){return false;});
		$S("#popupHistoryTable").manager().op.Storage.Trigger.select.add(page.leftTriggerFn);
		var historyList = Ccay.History.getHistory(getHistoryKey());
		var values =[];
		$.each(historyList,function(){
			if(Ccay.DataHelper.hasValue(this.value)){
				values.push(this.value);
			}
		})
		Ccay.doPost(servicePath, values,function(datas){ 
			//排序
			var sortDatas = [];
			
			$.each(values,function(){
				var value = this;
				$.each(datas,function(){
					if(Ccay.DataHelper.getObj(popupBean.uniqueKey, this) == value){
						sortDatas.push(this);
						return false;
					}
				});
			})

			var grid = $S("#popupHistoryTable").manager();
			var datas = grid.op.Storage.dataset = sortDatas;
			grid.reload();
		},function(){return true})
	
	}
	/**
	 * @description 初始化数据集合grid
	 */
	function initRightTable() {
		var columns = [{columnType: 'select',multi : true,field : popupBean.uniqueKey}];
		$.each(popupBean.columns,function(){
			if(this.id){
				this.field = this.id;
				if(this.id.indexOf("\.")){
					this.field = this.id;
					this.displayField = "{0} ? {1} : ''".formatText(this.field.split("\.")[0], this.field);
				}
			}
			if(!this.width){
				this.width = 110;
			}
			columns.push($.extend({},this));
		});
		var options={
			shiftSelectMode : false,
			customSetting:false,
			showPager:false,
			pageSize:popupBean.pageSize || Ccay.UI.Config.pager.defaultSize,
			pageSizeList:popupBean.pageSizeList || Ccay.UI.Config.pager.pageSizes,
			columns:columns ,
			width : popupBean.gridWidth || 445,
			autoLoad : false,
			height : 393,
			operation:{
				insert : {}
			},
			fnDataBindComplete:function(){
				var grid = this;
				if(grid.op.Storage.dataset.length > 0){
					setTimeout(function(){
						checkAllStatus(grid);
						allClickHandle(grid)
					},10)
					
				}
			}
		
		};
		var currRightOptions = $.type(popupBean.rightTableOptions) == "object" ? popupBean.rightTableOptions : (popupBean.event && popupBean.event.right);
		$S("#popupRightTable").igrid($.extend(options,currRightOptions)).delegate("tr.grid-row","dblclick",function(e){
			$(this).find("td.grid-select").click();
		}).bind('selectstart',function(){return false;});
		var rightStorage = $S("#popupRightTable").manager().op.Storage;
		rightStorage.Trigger.select.add(function(data, select){
			if(!select){
				var rightGrid = $S("#popupRightTable").manager(), leftGrid = $S("#popupLeftTable").manager();
				
				if(rightGrid.op.Storage.dataset.length == 0){
					return;
				}
				rightStorage.destroyItem(data._index);
				rightGrid.reBind();
				
				var tr = leftGrid.dom.find("td[val='{0}'].grid-select:first".formatValue(Ccay.DataHelper.getObj(popupBean.uniqueKey, data))).parent();
				if(tr.length){
					leftGrid.getRowData(tr.removeClass("igrid-selected"))._selected = false;
					leftGrid.setSelectHeader(false);
				} 
				if(historyGridInit){
					var historyGrid = $S("#popupHistoryTable").manager();
					var hisTr = historyGrid.dom.find("td[val='{0}'].grid-select:first".formatValue(Ccay.DataHelper.getObj(popupBean.uniqueKey, data))).parent();
					hisTr.length && (historyGrid.getRowData(hisTr.removeClass("igrid-selected"))._selected = false);
				}
			}
		})
		
		var selectedItems = popupBean.selectedItems || [];
		// js中通过分隔符split生产的数组，很有可能导致末尾为空字符，因此判断末尾数组元素是否是空的，是就删除末尾元素
		if (selectedItems.length > 0) {
			if (("" + selectedItems[selectedItems.length - 1]).length == 0) {
				selectedItems.pop();
			}			
			if(selectedItems.length > 0){
				Ccay.doPost(servicePath, selectedItems,function(datas){ 
					var grid = $S("#popupRightTable").manager();
					var datas = grid.op.Storage.dataset = datas || [];
					$.each(datas,function(){
						this._selected =true;
					});
					
					grid.reload();
					if(isInit == "wait"){
						cynchroLeftTable();
					}else{
						isInit = true;
					}
					setTimeout(function(){popupBean.hasHistory && cynchroOnSelected("#popupHistoryTable");},200);
				},function(){return true})
			}
		}
	}
	/**
	 * @description 页面初始化或重新查询的时候，通过右边已选数据，初始化左边table的item状态 【checkbox】
	 */
	function cynchroOnSelected(id) {
		var rightGrid = $S("#popupRightTable").manager(), grid = $S(id).manager();
		var selectedRecords = (rightGrid && rightGrid.op.Storage.dataset) || [];
		grid.op.Storage.each(function(data){data._selected =false});
		grid.reBind();
		$.each(selectedRecords, function() {
			var uniqueKeyValue = Ccay.DataHelper.getObj(popupBean.uniqueKey,this);
			var tr = grid.dom.find("td[val='{1}'].grid-select:first".formatValue(popupBean.uniqueKey,uniqueKeyValue)).parent();
			if(tr.length > 0){
				var data = grid.getRowData(tr.addClass("igrid-selected"));
				data._selected = true;
			}
		});

	}
	function checkAllStatus (grid,checked){
		 var tr = grid.getHeadPanel().find(".igrid-head tr");
		 if(checked !== true &&  checked !== false){
		 	 checked = grid.getSelectedRecords().length && grid.getSelectedRecords().length == grid.op.Storage.dataset.length;
		 }
		 checked ?  tr.not(".igrid-selected").addClass("igrid-selected") : tr.removeClass("igrid-selected");
	}
	function cynchroLeftTable() {
		var rightGrid = $S("#popupRightTable").manager(), leftGrid = $S("#popupLeftTable").manager();
		var selectedRecords = (rightGrid && rightGrid.op.Storage.dataset) || [];
		$.each(selectedRecords, function() {
			var uniqueKeyValue = Ccay.DataHelper.getObj(popupBean.uniqueKey,this);
			var tr = leftGrid.dom.find("td[val='{1}'].grid-select:first".formatValue(popupBean.uniqueKey,uniqueKeyValue)).parent();
			if(tr.length > 0){
				var data = leftGrid.getRowData(tr.addClass("igrid-selected"));
				data._selected = true;
			}
		});
		
		
	}

	/**
	 * @description 点击确认按钮后执行 1 得到popupBean中指定的回调函数的引用。（如果得不到引用则终止该方法） 2
	 *              得到已选项目，此为js对象，通过回调函数的传参返回。
	 */
	page.onOk = function() {
		var flag, rightGrid = $S("#popupRightTable").manager(), rowdatas =(rightGrid && rightGrid.op.Storage.dataset) || [];
		if(Ccay.History.isSupport(popupBean)){
			Ccay.History.saveList(popupBean.servicePath, rowdatas, popupBean.uniqueKey);
		}
		if ($.isFunction(popupBean.callback)) {
			flag = popupBean.callback(rowdatas);
		}
		if (flag !== false){
			page.closeDialog();
		}
	};


	/**
	 * @description 通过参数动态生成条件区域dom
	 * @param {object[]}
	 *            columns 列参数定义
	 * 
	 */
	function initConditionArea(columns, buttonIsCenter) {
		var hasSearchColumn = false;
		var length = columns.length, autoWidth = true;
		$.each(columns, function(index, column) {
					if (column.isCondition) {
						hasSearchColumn = true;
						$S("#popup_cond_div").append($i18n(column.header) + " ");
						$S("#popup_cond_div").append("<input type='text' style='width:120px' name='"+ column.id + "' maxlength='100'/>&nbsp;");
					}
					if (column.hidden)
						length--;
					if (column.width) {
						autoWidth = false;
					}
				});
		if (length <= 3 && autoWidth) {
			$.each(columns, function() {
						this.width = parseInt(330 / length);
					});
		}
		if (hasSearchColumn && buttonIsCenter){
			var btnHtml =['<br><br><center><SPAN id=btn_popup_mutil class="ccay-button search default" ><A class="ccay-icon search"></A><LABEL>'+ $.i18n.prop("ccay.common.button.search") +'</LABEL></SPAN>'];
			btnHtml.push('<SPAN  class="ccay-button reset" onclick =$(this).parents("form").ccayReset() ><A class="ccay-icon reset"></A><LABEL>'+ $.i18n.prop("ccay.common.button.reset") +'</LABEL></SPAN></center>')
			$S("#popup_cond_div").append(btnHtml.join(""));
		}else if(hasSearchColumn){
			var btnHtml =['<SPAN id=btn_popup_mutil class="ccay-button search default" ><A class="ccay-icon search"></A><LABEL>'+ $.i18n.prop("ccay.common.button.search") +'</LABEL></SPAN>'];
			btnHtml.push('<SPAN  class="ccay-button reset" onclick =$(this).parents("form").ccayReset() ><A class="ccay-icon reset"></A><LABEL>'+ $.i18n.prop("ccay.common.button.reset") +'</LABEL></SPAN>')
			$S("#popup_cond_div").append(btnHtml.join(""));
		}

	};
});
